<template>
  <div class="h-100% w-90%">
     <el-card class="m-t-20px">
        <div class="m-b-20px " v-if="importFileData.fileName">
                <div v-if="importFileData.uploadLoading" class="flex gap-10px ">
                    <span class="text-14px m-r-10px">{{t('deviceManage.upload_progress_label')}}:</span>
                    <el-progress class="w-300px" :percentage="importFileData.progress" :text-inside="true" :stroke-width="20" />
                </div>
                <div class="flex gap-10px m-t-10px">
                 <div class="text-14px">{{t('deviceManage.config_file_name_label')}}: </div>
                 <div class="text-14px">{{importFileData.fileName}}</div>
                 <el-button 
                 size="small" 
                 type="primary" 
                 @click="handleFileUpload"
                 :loading="importFileData.uploadLoading"
                 >{{ t('deviceManage.upload_file_label') }}</el-button>
                </div>    
            </div>
         <div >
            <el-input 
            v-model="exportFileData.fileContent" 
            type="textarea"
            :autosize="{ minRows: 10, maxRows: 20 }"
            ></el-input>
         </div>
         <div class="m-t-20px">
            <div class="flex items-center gap-10px">
                <div
                v-for="item in operationConfigList" 
                :key="item.key" 
                v-globalLoading="handleOperationConfig.bind(null,item.key)"
                class="global_btn"
                >
                    {{item.name}}
                </div>
                <input type="file" @change="handleFileChange" ref="fileInput" style="display: none;">
            </div>
         </div>
     </el-card>
  </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue'
export default defineComponent({
  name: 'apConfig',
})
</script>
<script setup  lang="ts">
import { useI18n } from 'vue-i18n'
import { ConfigManageApi } from '@/api/configManage'
import axios from 'axios'   
import  {ElNotificationFn} from '@/utils/computedUtils'
import {OtaApi} from '@/api/ota'
const { t } = useI18n()
const operationConfigList = ref<any[]>([
    {
        name:t('deviceManage.get_config_label'),
        key:'get_config',
        loading:false
    },
    {
        name:t('deviceManage.save_config_label'),
        key:'save_config',
        loading:false
    },
    {
        name:t('deviceManage.export_config_label'),
        key:'export_config',
        loading:false
    },
    {
        name:t('deviceManage.import_config_label'),
        key:'import_config',
        loading:false
    }
])
const handleOperationConfig = async (key:string) => {
    switch(key){
        case 'get_config':
           await exportConfig(key)
            break;
        case 'save_config':
            await saveConfig()
            break;
        case 'export_config':
            await exportConfig(key)
            break;
        case 'import_config':
            await importConfig(key)
            break;
    }
}
const exportFileData = ref<any>({
    fileContent:'',
    fileName:''
})
const fileInput = ref<any>(null)
const apIp = '192.168.10.1'
const apPort = 9999
async function exportConfig(key:string){
   const item = operationConfigList.value.find((item:any)=>item.key === key)
   item.loading = true
    try {
     const {data}:any=await ConfigManageApi.reqExportApConfig({
    port:apPort,
    id:0
    }) 
   exportFileData.value.fileName = 'ap_server_config.toml'
   const downloadUrl = data.addr
   const finalUrl = `${downloadUrl}?t=${new Date().getTime()}`
   const response = await axios({
    url: finalUrl,
    method: 'GET',
   })
   if(key==='get_config'){
    exportFileData.value.fileContent = response.data
    ElNotificationFn('success',t('deviceManage.get_config_success_label'))
   }else{
    const blob = new Blob([response.data])
    const a = document.createElement('a')
    a.href = window.URL.createObjectURL(blob)
    a.download = exportFileData.value.fileName
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    window.URL.revokeObjectURL(a.href)
   }
    } catch (error) {
      key==='get_config' ? ElNotificationFn('error',t('deviceManage.get_config_failure_label')) : ElNotificationFn('error',t('deviceManage.export_config_failure_label'))
    }finally{
        item.loading = false
    }
}
async function importConfig(key:string){
    if(key==='import_config'){
        fileInput.value.click()
        return
    }
    const item = operationConfigList.value.find((item:any)=>item.key === key)
    item.loading = true
    try {
        const formData = new FormData()
        formData.append('filedata',exportFileData.value.fileContent)
        formData.append('filename',exportFileData.value.fileName)
        formData.append('id',props.id)
        await ConfigManageApi.reqImportConfig(formData)
        ElNotificationFn('success',t('deviceManage.save_config_success_label'))
    } catch (error) {
        ElNotificationFn('error',t('save_config_failure_label'))
    }finally{
        item.loading = false
    }
}
async function saveConfig(){
    if(!exportFileData.value.fileContent){
        ElNotificationFn('warning',t('deviceManage.file_content_empty_label'))
        return
    }
    try {
        await ConfigManageApi.reqSaveConfig({
            port:apPort,
            fileData:exportFileData.value.fileContent,
            id:0
        })
        ElNotificationFn('success',t('deviceManage.save_config_success_label'))
    } catch (error) {
        ElNotificationFn('error',t('deviceManage.save_config_failure_label'))
    }finally{
      
    }
}
const importFileData = ref<any>({
    fileName:'',
    uploadLoading:false,
    progress:0,
    fileData:null,
    cancelToken:null
})
function handleFileChange(e:any) {
    const file = e.target.files[0]
    importFileData.value.fileName = file.name
    importFileData.value.fileData = file
}
async function handleFileUpload(){
    try {
    importFileData.value.uploadLoading = true
    const reader = new FileReader()
    const fileContent = await new Promise((resolve, reject) => {
            reader.onload = (e) => resolve(e.target?.result)
            reader.onerror = (e) => reject(e)
            reader.readAsText(importFileData.value.fileData)
        })
    const data = {
        id:0,
        filename:importFileData.value.fileName,
        fileData: fileContent
    }
    importFileData.value.cancelToken = axios.CancelToken.source()
    await ConfigManageApi.reqSaveConfig(data
         ,(progressEvent:any)=>{
        importFileData.value.progress = Math.round((progressEvent.loaded / progressEvent.total) * 100)},
        importFileData.value.cancelToken.token
    )
    ElNotificationFn('success',t('deviceManage.import_config_success_label'))
    } catch (error) {
        ElNotificationFn('error',t('deviceManage.import_config_failure_label'))
    }finally{
        importFileData.value.uploadLoading = false
        importFileData.value.fileName = ''
    }
   
}
</script>

<style  lang="scss" scoped>
@import '@/styles/card.scss';
@import '@/styles/input.scss';
:deep(.el-textarea__inner){
  background-color: #1e1e1e;
  box-shadow: none;
  color: #fff;
}
:deep(.el-textarea__inner){
  background-color: #1e1e1e;
  box-shadow: none;
  color: #fff;

  /* 滚动条整体样式 */
  &::-webkit-scrollbar {
    width: 15px;
    height: 15px;
  }
  
  /* 滚动条轨道 */
  &::-webkit-scrollbar-track {
    background: #2c2c2c;
    border-radius: 3px;
  }
  
  /* 滚动条滑块 */
  &::-webkit-scrollbar-thumb {
    background: #666;
    border-radius: 3px;
    
    &:hover {
      background: #808080;
    }
  }
}
</style>
